<template>
  <div class="party-form-container">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="party-form">
      <el-form-item label="当事人名称" prop="party_name">
        <el-input v-model="formData.party_name" placeholder="请输入当事人名称" />
      </el-form-item>

      <el-form-item label="当事人类型" prop="party_type">
        <el-select v-model="formData.party_type" placeholder="请选择当事人类型">
          <el-option :value="1" label="个人" />
          <el-option :value="2" label="企业" />
        </el-select>
      </el-form-item>

      <el-form-item label="委托身份" prop="is_client">
        <el-select v-model="formData.is_client" placeholder="请选择委托身份">
          <el-option :value="1" label="委托人" />
          <el-option :value="2" label="对方当事人" />
          <el-option :value="3" label="第三人" />
        </el-select>
      </el-form-item>

      <el-form-item label="诉讼地位" prop="relationship">
        <el-select v-model="formData.relationship" placeholder="请选择诉讼地位">
          <el-option :value="1" label="原告" />
          <el-option :value="2" label="被告" />
          <el-option :value="3" label="第三人" />
          <el-option :value="4" label="上诉人" />
          <el-option :value="5" label="被上诉人" />
          <el-option :value="6" label="再审申请人" />
          <el-option :value="7" label="再审被申请人" />
          <el-option :value="8" label="申请执行人" />
          <el-option :value="9" label="被申请执行人" />
        </el-select>
      </el-form-item>

      <el-form-item label="证件号码" prop="id_number">
        <el-input v-model="formData.id_number" placeholder="请输入证件号码" />
      </el-form-item>

      <el-form-item label="联系人" prop="contact">
        <el-input v-model="formData.contact" placeholder="请输入联系人" />
      </el-form-item>

      <el-form-item label="联系电话" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item v-if="!isEdit">
        <el-button type="primary" @click="submitForm">
          {{ isEdit ? '确认更新' : '确认' }}
        </el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import request from '@/utils/request'

  // 定义Props接口
  interface Props {
    isEdit?: boolean
    caseId?: number
    partyData?: any
  }

  // 定义Emits接口
  const emit = defineEmits(['success', 'cancel'])

  // 定义Props
  const props = withDefaults(defineProps<Props>(), {
    isEdit: false,
    caseId: 0,
    partyData: () => ({}),
  })

  // 表单引用
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive({
    id: 0,
    case_id: props.caseId,
    party_name: '',
    party_type: 1, // 默认为个人
    is_client: 1, // 默认为委托人
    relationship: 1, // 默认为原告
    id_number: '',
    contact: '',
    mobile: '',
  })

  // 表单验证规则
  const rules = reactive<FormRules>({
    party_name: [
      { required: true, message: '请输入当事人名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    ],
    party_type: [{ required: true, message: '请选择当事人类型', trigger: 'change' }],
    is_client: [{ required: true, message: '请选择是否为委托人', trigger: 'change' }],
    relationship: [{ required: true, message: '请选择诉讼地位', trigger: 'change' }],
    mobile: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  })

  // 初始化
  onMounted(() => {
    if (props.isEdit && props.partyData) {
      // 编辑模式，填充表单数据
      formData.id = props.partyData.id || 0
      formData.case_id = props.caseId
      formData.party_name = props.partyData.partyName || props.partyData.party_name || ''
      formData.party_type = props.partyData.partyType || props.partyData.party_type || 1

      // 根据is_client_text设置is_client值
      const clientTypeMap: Record<string, number> = {
        委托人: 1,
        对方当事人: 2,
        第三人: 3,
      }
      formData.is_client = clientTypeMap[props.partyData.is_client_text] || 1

      // 根据relationship_text设置relationship值，与后端保持一致
      const relationshipMap: Record<string, number> = {
        未知: 0,
        原告: 1,
        被告: 2,
        第三人: 3,
        上诉人: 4,
        被上诉人: 5,
        再审申请人: 6,
        再审被申请人: 7,
        申请执行人: 8,
        被申请执行人: 9,
      }
      formData.relationship = relationshipMap[props.partyData.relationship_text] || 1

      formData.id_number = props.partyData.idNumber || props.partyData.id_number || ''
      formData.contact = props.partyData.contactPerson || props.partyData.contact || ''
      formData.mobile =
        props.partyData.contactPhone || props.partyData.phone || props.partyData.mobile || ''
    }
  })

  // 监听props.partyData的变化，确保表单数据能及时更新
  watch(
    () => props.partyData,
    newVal => {
      if (props.isEdit && newVal) {
        // 编辑模式，填充表单数据
        formData.id = newVal.id || 0
        formData.case_id = props.caseId
        formData.party_name = newVal.partyName || newVal.party_name || ''
        formData.party_type = newVal.partyType || newVal.party_type || 1

        // 根据is_client_text设置is_client值
        const clientTypeMap: Record<string, number> = {
          委托人: 1,
          对方当事人: 2,
          第三人: 3,
        }
        formData.is_client = clientTypeMap[newVal.is_client_text] || 1

        // 根据relationship_text设置relationship值，与后端保持一致
        const relationshipMap: Record<string, number> = {
          未知: 0,
          原告: 1,
          被告: 2,
          第三人: 3,
          上诉人: 4,
          被上诉人: 5,
          再审申请人: 6,
          再审被申请人: 7,
          申请执行人: 8,
          被申请执行人: 9,
        }
        formData.relationship = relationshipMap[newVal.relationship_text] || 1

        formData.id_number = newVal.idNumber || newVal.id_number || ''
        formData.contact = newVal.contactPerson || newVal.contact || ''
        formData.mobile = newVal.contactPhone || newVal.phone || newVal.mobile || ''
      } else if (!props.isEdit) {
        // 新增模式，重置表单数据
        formData.id = 0
        formData.case_id = props.caseId
        formData.party_name = ''
        formData.party_type = 1
        formData.is_client = 1
        formData.relationship = 1
        formData.id_number = ''
        formData.contact = ''
        formData.mobile = ''
      }
    },
    { deep: true, immediate: true }
  )

  // 提交表单
  const submitForm = async (force = false) => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid, fields) => {
      if (valid) {
        try {
          // 根据模式选择API，使用正确的路由路径
          const apiUrl = props.isEdit ? '/api/lawcase/parties/edit' : '/api/lawcase/parties/add'

          // 根据模式选择请求方法
          const method = props.isEdit ? 'put' : 'post'

          // 复制formData，确保不修改原数据
          // 使用类型断言让TypeScript允许添加额外的force属性
          const submitData = { ...formData } as typeof formData & { force?: number }

          // 如果是添加模式且需要强制添加（忽略重复检查），添加force参数
          if (!props.isEdit && force) {
            submitData.force = 1
          }

          const response: any = await request({
            url: apiUrl,
            method: method,
            data: submitData,
          })

          if (response.code === 0) {
            ElMessage.success(props.isEdit ? '编辑成功' : '添加成功')
            emit('success', submitData)
          } else {
            ElMessage.error(response.msg || (props.isEdit ? '编辑失败' : '添加失败'))
          }
        } catch (error) {
          ElMessage.error(props.isEdit ? '编辑失败，请重试' : '添加失败，请重试')
        }
      } else {
      }
    })
  }

  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }

  // 手动刷新表单数据
  const refreshForm = (data: any) => {
    if (props.isEdit && data) {
      // 直接更新表单数据
      formData.id = data.id || 0
      formData.case_id = props.caseId
      formData.party_name = data.partyName || data.party_name || ''
      formData.party_type = data.partyType || data.party_type || 1

      // 根据is_client_text设置is_client值
      const clientTypeMap: Record<string, number> = {
        委托人: 1,
        对方当事人: 2,
        第三人: 3,
      }
      formData.is_client = clientTypeMap[data.is_client_text] || 1

      // 根据relationship_text设置relationship值，与后端保持一致
      const relationshipMap: Record<string, number> = {
        未知: 0,
        原告: 1,
        被告: 2,
        第三人: 3,
        上诉人: 4,
        被上诉人: 5,
        再审申请人: 6,
        再审被申请人: 7,
        申请执行人: 8,
        被申请执行人: 9,
      }
      formData.relationship = relationshipMap[data.relationship_text] || 1

      formData.id_number = data.idNumber || data.id_number || ''
      formData.contact = data.contactPerson || data.contact || ''
      formData.mobile = data.contactPhone || data.phone || data.mobile || ''
    }
  }

  // 暴露方法给父组件
  defineExpose({
    submitForm,
    refreshForm,
  })
</script>

<style scoped>
  .party-form-container {
    padding: 20px 0;
  }

  .party-form {
    max-width: 600px;
  }
</style>
